<?php
Zend_Loader::loadClass("Application_Ajax_Server_Function");
Zend_Loader::loadClass('Materials');
class GetMaterialDetailsById extends Application_Ajax_Server_Function
{
	public function call() {
		$id = (int) $this->_params['id'];
		$materiali = new Materials();
		
		$recordSet = $materiali->find($id);
		$materiale = $recordSet->current();
		$props_physical = $materiale->findDependentRowset("MaterialPropsPhysical");
		$props_thermal = $materiale->findDependentRowset("MaterialPropsThermal");
		$props_ecarbon = $materiale->findDependentRowset("MaterialPropsEcarbon");
		
		// Build prev/next circular array
		if (!$materiale->id_category) {
			$recordSet = $materiali->select()->from($materiali, array("id"))
			->where("id_category is null")
			->where("status > ?", 0)
			->order("name");
		} else {
			$recordSet = $materiali->select()->from($materiali, array("id"))
			->where("id_category = ?", $materiale->id_category)
			->where("status > ?", 0)
			->order("name");
		}
		
		$ids = $materiali->fetchAll($recordSet)->toArray();
		foreach ($ids as $k => $v)
		{
			if($v["id"] == $id)
			{
				if (isset($ids[$k-1]))
					$prev = $ids[$k-1];
				else
					$prev = end($ids);
				if (isset($ids[$k+1]))
					$next = $ids[$k+1];
				else
					$next = $ids[0];
			}
		}
		
		$result = array(
				$materiale->toArray(),
				'category' => $materiale->findParentRow('MaterialCategories')->name,
				'props' => array (
						'physical' => $props_physical->toArray(),
						'thermal'  => $props_thermal->toArray(),
						'ecarbon'  => $props_ecarbon->toArray(),
				),
				'prev' => $prev["id"],
				'next' => $next["id"]
		
		);
		
		return $result;
	}
}
